import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi, getUserInfoApi, logoutApi } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/storage'
import type { LoginRequest, UserInfo } from '@/types/api/auth'
import type { API } from '@/types/api/response'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

interface AuthState {
  userInfo: UserInfo | null
  token: string | null | undefined
  loading: boolean
  permissions: string[]
  roles: string[]
}

export const useAuthStore = defineStore('auth', () => {
  // 用户信息
  const userInfo = ref<UserInfo | null>(null)
  
  // token
  const token = ref<string | null | undefined>(getToken())
  
  // 加载状态
  const loading = ref<boolean>(false)
  
  // 权限列表
  const permissions = ref<string[]>([])
  
  // 角色列表
  const roles = ref<string[]>([])
  
  /**
   * 登录
   * @param username 用户名
   * @param password 密码
   */
  const login = async (username: string, password: string): Promise<boolean> => {
    try {
      loading.value = true
      const loginData: LoginRequest = { username, password }
      const res = await loginApi(loginData)
      
      if (res.success && res.data.token) {
        // 保存token
        token.value = res.data.token
        setToken(res.data.token)
        
        // 获取用户信息
        await fetchUserInfo()
        return true
      }
      return false
    } catch (error) {
      const { t } = useI18n()
      message.error(t('auth.loginFailed'))
      return false
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 获取用户信息
   */
  const fetchUserInfo = async (): Promise<UserInfo | null> => {
    try {
      if (!token.value) {
        return null
      }
      
      const res = await getUserInfoApi()
      if (res.success && res.data) {
        userInfo.value = res.data
        permissions.value = res.data.permissions || []
        roles.value = res.data.roles || []
        return res.data
      }
      return null
    } catch (error) {
      const { t } = useI18n()
      message.error(t('auth.getUserInfoFailed'))
      return null
    }
  }
  
  /**
   * 退出登录
   */
  const logoutAction = async (): Promise<boolean> => {
    try {
      if (token.value) {
        const res = await logoutApi()
        if (!res.success) {
          return false
        }
      }
      
      // 清理状态
      resetState()
      return true
    } catch (error) {
      const { t } = useI18n()
      message.error(t('auth.logoutFailed'))
      return false
    }
  }
  
  /**
   * 重置状态
   */
  const resetState = (): void => {
    // 清理token
    token.value = null
    removeToken()
    
    // 清理用户信息
    userInfo.value = null
    permissions.value = []
    roles.value = []
  }
  
  /**
   * 判断是否有权限
   * @param permission 权限标识
   */
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission)
  }

  /**
   * 获取当前状态
   */
  const getState = (): AuthState => {
    return {
      userInfo: userInfo.value,
      token: token.value,
      loading: loading.value,
      permissions: permissions.value,
      roles: roles.value
    }
  }
  
  return {
    userInfo,
    token,
    loading,
    permissions,
    roles,
    login,
    fetchUserInfo,
    logoutAction,
    resetState,
    hasPermission,
    getState
  }
}) 